<?php
/**
 * 
 * 
 * 文件描述：生成验证码的类
 * 
 * 
 * 
 */

class PassCode{
	
	public $randCode;    //生成的验证码字符串
	private $codeLength;//生成的验证码的长度
	private $codeSize; //生成的验证码的字体大小
	private $imageHeight;//图片的宽度
	private $imageWidth;//图片的高度
	private $imageBoder;//图片是否需要边框
	private $imageId;//图象的标识符
	private $disturbColor; //干扰像素的颜色randStr
	
	public function __construct($codeLength=4, $codeSize=5, $imageHeight=30, $imageWidth=80, $imageBoder=true){
		$this->codeLength=$codeLength;
		$this->codeSize=$codeSize;
		$this->imageHeight=$imageHeight;
		$this->imageWidth=$imageWidth;
		$this->imageBoder=$imageBoder;
	}
	
	public function outImg(){
		header ("Content-type: image/png");
		$this->randCode = $this->getRandStr($this->codeLength);//产生验证码
//		echo $this->randCode;
//		exit();
//		$this->randCode = '2r44';
		$this->createImage();//产生图片
		$this->setDisturbColor();//设置干扰像素
		$this->writeImage2();//往图片上写验证码

		imagepng($this->imageId);//生成图片
		imagedestroy($this->imageId);//销毁图片

		return $this->randCode;
	}
	
	//产生验证码图片
	private function createImage(){
		$this->imageId = @imagecreate($this->imageWidth,$this->imageHeight);
		$white = imagecolorallocate($this->imageId,255,255,255);
		$black = imagecolorallocate($this->imageId,0,0,0);
		imagefilledrectangle($this->imageId,0,0,$this->imageWidth-1,$this->imageHeight-1,$white);//白色底
		if($this->imageBoder)
			imagerectangle($this->imageId,0,0,$this->imageWidth-1,$this->imageHeight-1,$black);// 黑色边框
	}

	//设置图片的干扰像素
	private function setDisturbColor(){
		for ($i=0;$i<=100;$i++){
			$this->disturbColor = imagecolorallocate($this->imageId, rand(0,255), rand(0,255), rand(0,255));
			imagesetpixel($this->imageId, rand(2, $this->imageWidth), rand(2, $this->imageHeight), $this->disturbColor);
    //magesetpixel()在图像中用color颜色在 x，y 坐标（图像左上角为 0，0）上画一个点。
		}
	}
	
//在验证码图片上逐个画上验证码
	private function writeImage(){
		$black = imagecolorallocate($this->imageId,0,0,0);
		imagestring($this->imageId, $this->codeSize, 0, 0, $this->randCode, $black);
	}
	
	private function writeImage2(){
		for ($i=0;$i<=$this->codeLength;$i++){
		    //设置随机颜色值
			$randColor = imagecolorallocate ($this->imageId, rand(0,255), rand(0,128), rand(0,255));
			$x = floor($this->imageWidth/$this->codeLength)*$i+5;
			$y = rand(0,$this->imageHeight-15);//上下位置随机
			    //$y=floor($this->imageHeight/3);//分成三份，放在中间
			imagechar($this->imageId, $this->codeSize, $x, $y, $this->randCode[$i], $randColor);
		}
	}
	
	//产生验证码
	public function getRandStr($strLength = 4){
		$strLength=$this->codeLength;

		$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';

		$result = '';
		$str_length = strlen($str)-1;
		for($i = 0;$i< $strLength;$i++){
			$num = rand(0,$str_length);
			$result .= $str[$num];
		}
		return $result;
	}

	function __destruct(){
		unset($this->codeLength, $this->imageHeight, $this->imageWidth, $this->imageBoder);
	}
	
}


			

?>